package com.pansoft.openplanet.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.http.EFHttpRequest;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.ChainParamsUtil;
import com.pansoft.openplanet.util.EosNetParamUtil;
import com.pansoft.openplanet.util.TCRequestUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author will
 * 切换钱包
 */
public class WalletChangeActivity extends BaseActivity {

    public static final String TAG = "WalletChangeActivity";
    private WalletListAdapter adapter;
    AccountDao accountDao = new AccountDao(this);
    private List<Account> datas = new ArrayList<>();
    List<String> accountNameList = new ArrayList<>();
    private int type = IPAssetsConstant.CHAIN_ID_ETH;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.star_asset_activity_wallet_change);
        if (getIntent() != null && getIntent().getExtras() != null) {
            type = getIntent().getIntExtra("wallet_type", IPAssetsConstant.CHAIN_ID_ETH);
        }
        initView();
        initData();
    }

    private void initView() {
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        String name = "";
        /*if (type == IPAssetsConstant.CHAIN_ID_ETH) {
            name = "ETH";
        } else if (type == IPAssetsConstant.CHAIN_ID_BTC) {
            name = "BTC";
        } else if (type == EosNetParamUtil.getEosChainId()) {
            name = "EOS";
        } else if (type == IPAssetsConstant.CHAIN_ID_ACT) {
            name = "ACT";
        } else if (type == IPAssetsConstant.CHAIN_ID_BCH) {
            name = "BCH";
        } else if (type == IPAssetsConstant.CHAIN_ID_ETE) {
            name = "ETE";
        }*/
        name = ChainParamsUtil.getAssetUnitByChainId(type);
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_asset_wallet_change_switch) +" "+
                name +" "+ ResStringUtil.getString(R.string.open_planet_asset_wallet_change_wallet));
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new WalletListAdapter(this, R.layout.star_asset_item_wallet_change_list, datas);
        recyclerView.setAdapter(adapter);
    }

    private void initData() {
        if (type == IPAssetsConstant.CHAIN_ID_ETH) {
            datas.addAll(accountDao.getAllChildAccount(IPAssetsConstant.ChainEnum.ETH));

        } else if (type == IPAssetsConstant.CHAIN_ID_BTC) {
            datas.addAll(accountDao.getAllChildAccount(IPAssetsConstant.ChainEnum.BTC));

        } else if (type == EosNetParamUtil.getEosChainId()) {
            datas.addAll(accountDao.getAllChildAccount(EosNetParamUtil.getEosChainEnum()));
            for (Account account : datas) {
                if (!account.isActivate()) {
                    verifyIsActive(account.getPublicKey(), account.getEosActivePubKey());
                }
            }
        }else if (type == IPAssetsConstant.CHAIN_ID_ACT) {
            datas.addAll(accountDao.getAllChildAccount(IPAssetsConstant.ChainEnum.ACHAIN));
        } else if (type == IPAssetsConstant.CHAIN_ID_BCH) {
            datas.addAll(accountDao.getAllChildAccount(IPAssetsConstant.ChainEnum.BCH));
        }else if (type == IPAssetsConstant.CHAIN_ID_ETE) {
            datas.addAll(accountDao.getAllChildAccount(IPAssetsConstant.ChainEnum.ETE));
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 验证是否被激活，如果返回账号，则被激活
     * 更新数据库的账户地址
     * 再取更新后的账户，更新accountNames字段和isActive字段
     *
     * @param pubKey       　ｋｅｙ
     * @param activePubKey 　ｋｅｙ
     */
    private void verifyIsActive(String pubKey, String activePubKey) {
        final Account account = accountDao.getEosAccountByActivePublicKey(activePubKey);
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("ownerPublicKey", pubKey);
        hashMap.put("activePublicKey", activePubKey);
        hashMap.put("chainId", type + "");
        //http://tc.solarsource.cn:9692/tcserver/eos/getAccount?accountName=eosio
        TCRequestUtil.getCommonRequest(TAG, "eos/getKeyAccountsByKey", hashMap,
                new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    accountNameList.clear();
                    if (jsonObject.optString("result").equals("success")) {
                        JSONArray dataArray = jsonObject.optJSONObject("data").optJSONArray("account_names");
                        if (dataArray.length() > 0) {
                            for (int i = 0; i < dataArray.length(); i++) {
                                String accountName = dataArray.optString(i);
                                accountNameList.add(accountName);
                            }
                            accountDao.updateEosAccountName(account.getAddress(), accountNameList.get(0));
                            Account newAccount = accountDao.getAccount(accountNameList.get(0));
                            StringBuilder stringBuilder = new StringBuilder();
                            for (String account : accountNameList) {
                                stringBuilder.append(account).append("_");
                            }
                            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                            String eosAccountNames = stringBuilder.toString();
                            newAccount.setEosAccountNames(eosAccountNames);
                            newAccount.setActivate(true);
                            //激活成功，存本地
                            accountDao.insertOrReplace(newAccount);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EFHttpRequest.cancelRequest(TAG);
    }

    public class WalletListAdapter extends CommonAdapter<Account> {

        private Context context;

        public WalletListAdapter(Context context, int layoutId, List<Account> datas) {
            super(context, layoutId, datas);
            this.context = context;
        }

        @Override
        protected void convert(ViewHolder holder, final Account account, final int position) {
            ImageView ivSelected;
            ImageView ivIcon;
            TextView tvName;

            ivSelected = holder.getView(R.id.iv_selected);
            ivIcon = holder.getView(R.id.iv_icon);
            tvName = holder.getView(R.id.tv_name);

            if (account.isCurrentShow()) {
                ivSelected.setVisibility(View.VISIBLE);
            } else {
                ivSelected.setVisibility(View.INVISIBLE);
            }

            if (account.getAccountAvatar() == null || account.getAccountAvatar().equals("")) {
                if (type == IPAssetsConstant.CHAIN_ID_BTC) {
                    LXGlideImageLoader.getInstance().displayRoundCornerImage(mContext, ivIcon,
                            R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
                } else {
                    LXGlideImageLoader.getInstance().displayRoundCornerImage(mContext, ivIcon,
                            R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
                }
            } else {
                if (type == IPAssetsConstant.CHAIN_ID_BTC) {
                    LXGlideImageLoader.getInstance().displayRoundCornerImage(context, ivIcon, account.getAccountAvatar(),
                            R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
                } else {
                    LXGlideImageLoader.getInstance().displayRoundCornerImage(context, ivIcon, account.getAccountAvatar(),
                            R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
                }
            }
            tvName.setText(account.getAcccountName());
            holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    /*if (type == IPAssetsConstant.CHAIN_ID_ETH ) {
                        account.setCurrentShow(true);
                        //更新数据库
                        accountDao.updateCurrentShowAccount(IPAssetsConstant.ChainEnum.ETH, account.getAddress());
                    } else if (type == IPAssetsConstant.CHAIN_ID_ETE ) {
                        account.setCurrentShow(true);
                        //更新数据库
                        accountDao.updateCurrentShowAccount(IPAssetsConstant.ChainEnum.ETE, account.getAddress());
                    } else if (type == IPAssetsConstant.CHAIN_ID_BTC) {
                        account.setCurrentShow(true);
                        //更新数据库
                        accountDao.updateCurrentShowAccount(IPAssetsConstant.ChainEnum.BTC, account.getAddress());
                    } else if (type == EosNetParamUtil.getEosChainId()) {
                        account.setCurrentShow(true);
                        //更新数据库
                        accountDao.updateCurrentShowAccount(EosNetParamUtil.getEosChainEnum(), account.getAddress());
                    } else if (type == IPAssetsConstant.CHAIN_ID_BCH) {
                        account.setCurrentShow(true);
                        //更新数据库
                        accountDao.updateCurrentShowAccount(IPAssetsConstant.ChainEnum.BCH, account.getAddress());
                    } else if (type == IPAssetsConstant.CHAIN_ID_ACT) {
                        account.setCurrentShow(true);
                        //更新数据库
                        accountDao.updateCurrentShowAccount(IPAssetsConstant.ChainEnum.ACHAIN, account.getAddress());
                    }
*/
                    account.setCurrentShow(true);
                    //更新数据库
                    accountDao.updateCurrentShowAccount(IPAssetsConstant.ChainEnum.getChainEnumByChainName(ChainParamsUtil.getAssetUnitByChainId(type)), account.getAddress());

                    for (int i = 0; i < datas.size(); i++) {
                        if (i != position) {
                            account.setCurrentShow(false);
                        }
                    }
                    notifyDataSetChanged();
                    //通知WalletListFragment界面，更新数据刷新界面
                    EventBus.getDefault().post(account);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 600);
                }
            });
        }
    }

}
